from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import JsonResponse
from .forms import LoginForm
from .models import User
from .utils import HuanghuaiSpider
import json

def login_view(request):
    """登录视图"""
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            major_name = form.cleaned_data['major_name']
            
            # 创建爬虫实例
            spider = HuanghuaiSpider()
            
            # 尝试登录教务系统
            if spider.login(username, password):
                # 登录成功，保存用户信息到数据库
                try:
                    user = User.objects(username=username).first()
                    if user:
                        user.password = password
                        user.save()
                    else:
                        user = User(username=username, password=password)
                        user.save()
                except Exception as e:
                    print(f"保存用户信息失败: {e}")
                
                # 将用户信息和专业名称存储到session
                request.session['username'] = username
                request.session['password'] = password
                request.session['major_name'] = major_name
                request.session['logged_in'] = True
                
                # 重定向到课程表页面
                return redirect('course_schedule')
            else:
                messages.error(request, '登录失败，请检查用户名和密码')
    else:
        form = LoginForm()
    
    return render(request, 'jwxt/login.html', {'form': form})

def course_schedule_view(request):
    """课程表视图"""
    if not request.session.get('logged_in'):
        return redirect('login')
    
    username = request.session.get('username')
    password = request.session.get('password')
    major_name = request.session.get('major_name')
    
    spider = HuanghuaiSpider()
    
    # 重新登录以确保session有效
    if spider.login(username, password):
        # 获取课程表
        lessons = spider.get_course_schedule(major_name)
        
        # 组织课程表数据为表格形式
        schedule_table = {}
        weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        periods = ['上午', '下午', '晚上']
        sections = ['一', '二', '三', '四', '五']  # 一天5节大课
        
        # 初始化表格（按实际时间段分配节次）
        # 上午：第一、二节
        # 下午：第三、四节  
        # 晚上：第五节
        schedule_table = {
            '上午': {
                '一': {weekday: '' for weekday in weekdays},
                '二': {weekday: '' for weekday in weekdays}
            },
            '下午': {
                '三': {weekday: '' for weekday in weekdays},
                '四': {weekday: '' for weekday in weekdays}
            },
            '晚上': {
                '五': {weekday: '' for weekday in weekdays}
            }
        }
        
        # 填充课程数据
        for lesson in lessons:
            period = lesson['period']
            section = lesson['section']
            weekday = lesson['weekday']
            course = lesson['course']
            
            if period in schedule_table and section in schedule_table[period]:
                schedule_table[period][section][weekday] = course
        
        context = {
            'username': username,
            'major_name': major_name,
            'schedule_table': schedule_table,
            'weekdays': weekdays,
            'periods': periods,
            'sections': sections
        }
        
        return render(request, 'jwxt/course_schedule.html', context)
    else:
        messages.error(request, '获取课程表失败，请重新登录')
        return redirect('login')

def grades_view(request):
    """成绩查询视图"""
    if not request.session.get('logged_in'):
        return redirect('login')
    
    username = request.session.get('username')
    password = request.session.get('password')
    
    spider = HuanghuaiSpider()
    
    # 重新登录以确保session有效
    if spider.login(username, password):
        # 获取成绩信息
        grades_data = spider.get_grades()
        
        context = {
            'username': username,
            'grades_data': grades_data
        }
        
        return render(request, 'jwxt/grades.html', context)
    else:
        messages.error(request, '获取成绩失败，请重新登录')
        return redirect('login')

def logout_view(request):
    """登出视图"""
    request.session.flush()
    return redirect('login')


def bilibili_extract_page(request):
    """Bilibili 提取视频页面"""
    return render(request, 'jwxt/bilibili_extract.html')


def bilibili_summarize_page(request):
    """Bilibili 生成总结页面"""
    return render(request, 'jwxt/bilibili_summarize.html')